<template>
    <el-breadcrumb class="app-breadcrumb" separator="/">
        <transition-group name="breadcrumb">
            <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
                <span v-if="item.redirect === 'noRedirect' || index === levelList.length - 1" class="no-redirect">{{
                    item.meta.title }}</span>
                <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
            </el-breadcrumb-item>
        </transition-group>
    </el-breadcrumb>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const levelList = ref([]);

const getBreadcrumb = () => {
    let matched = route.matched.filter(item => item.meta && item.meta.title);
    const first = matched[0];

    // 如果第一个路由不是首页，并且它有 meta.title，则添加首页到面包屑
    // (根据你的项目需求调整，这里假设根路径 '/' 是首页)
    if (!isDashboard(first)) {
        // 假设首页路由配置了 meta: { title: '首页', breadcrumb: false (可选，如果不想首页也显示在面包屑里) }
        // 或者直接添加一个固定的首页项
        matched = [{ path: '/', meta: { title: '首页' }}].concat(matched)
    }

    levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false);
};

const isDashboard = (routeItem) => {
    const name = routeItem && routeItem.name;
    if (!name) {
        return false;
    }
    return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase(); // 假设首页路由名为 Dashboard
};

const handleLink = (item) => {
    const { redirect, path } = item;
    if (redirect) {
        router.push(redirect);
        return;
    }
    router.push(path);
};

watch(route, () => {
    getBreadcrumb();
}, { immediate: true });

</script>

<style scoped>
.app-breadcrumb.el-breadcrumb {
    display: inline-block;
    font-size: 14px;
    line-height: 50px;
    /* 与 Navbar 高度一致 */
    margin-left: 8px;
}

.no-redirect {
    color: #97a8be;
    cursor: text;
}

/* breadcrumb transition */
.breadcrumb-enter-active,
.breadcrumb-leave-active {
    transition: all .5s;
}

.breadcrumb-enter-from,
.breadcrumb-leave-active {
    opacity: 0;
    transform: translateX(20px);
}

.breadcrumb-leave-active {
    position: absolute;
}
</style>